package com.guigu.qingcheng.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.guigu.qingcheng.pojo.TbSku;
import com.guigu.qingcheng.pojo.TbSpu;
import com.guigu.qingcheng.pojo.vo.Goods;
import com.guigu.qingcheng.sevice.GoodsServiceFeign;
import com.guigu.qingcheng.utils.R;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class PageInfo {

    @Autowired
    private GoodsServiceFeign goodsServiceFeign;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     *详细页删除队列
     * @param skus
     */
    @RabbitListener(queues = "queue.delete")
    public void delete(List<TbSku> skus){
        File dir = new File("D:\\item\\");//文件存放路径
        for (TbSku sku:skus) {
            File dest = new File(dir,sku.getId()+".html");//获取指定文件
            //删除
            boolean result = false;
            int tryCount = 0;
            while(!result && tryCount++ <10)
            {
                System.gc();
                result = dest.delete();
            }
        }
    }

    /**
     * 详细页生成对列
     * @param skus
     */
    @RabbitListener(queues = "queue.generate")
    public void generate(List<TbSku> skus){
        ModelAndView model = new ModelAndView();
        //1.查询商品信息
        Goods goods = null;
        if (skus.size()==0)
        {

        }else {
            goods = goodsServiceFeign.queryBySpuId(skus.get(0).getSpuId());
        if (goods.getSkuList() == null || goods.getSpu() == null) {
            throw new RuntimeException("该商品以下架或者不存在");
        }

        TbSpu spu=goods.getSpu();

        List<TbSku> skuList=goods.getSkuList();

        // 创建一个Map容器
        Map<String,Object> mapObject=new HashMap<>();

        // 查询商品的一二三级分类
        List<R> category=new ArrayList<>();
        category.add(goodsServiceFeign.detail(spu.getCategory1Id()));
        category.add(goodsServiceFeign.detail(spu.getCategory2Id()));
        category.add(goodsServiceFeign.detail(spu.getCategory3Id()));
        mapObject.put("category",category);
        model.addObject("category",category);

        // sku地址列表
        Map<String,String> urlMap=new HashMap<>();
        for (TbSku sku:skuList){
            if ("1".equals(sku.getStatus())) {
                String jsonString = JSON.toJSONString(JSON.parseObject(sku.getSpec()), SerializerFeature.MapSortField);
                urlMap.put(jsonString, sku.getId() + ".html");
            }
        }

        for (TbSku sku:skuList) {
            Context context = new Context();
            Map<String, Object> map = new HashMap<>();
            map.put("spu", spu);
            map.put("sku", sku);

            if (sku.getImages() != null) {
                if (sku.getImages().length() > 0) {
                    map.put("skuImages", sku.getImages().split(",")); // spu图片列表
                }
            }
            if (spu.getImages() != null) {
                if (spu.getImages().length() > 0) {
                    map.put("spuImages", spu.getImages().split(",")); //sku图片列表
                }
            }

            Map paraItems = JSON.parseObject(spu.getParaItems()); //参数列表
            map.put("paraItems", paraItems);
            Map<String, String> specItems = (Map) JSON.parseObject(sku.getSpec()); // 规格列表
            map.put("specItems", specItems);

            Map<String, List> specMap = (Map) JSON.parseObject(spu.getSpecItems());
            for (String key : specMap.keySet()) {
                List<String> list = specMap.get(key);
                List<Map> mapList = new ArrayList<>();
                // 循环规格
                for (String value : list) {
                    Map map1 = new HashMap();
                    map1.put("option", value); // 规格选项
                    //System.out.println(map1);
                    // 是否和sku的规格相同，就选中
                    if (specItems.get(key).equals(value)) {
                        //System.out.println(specItems.get(key));
                        map1.put("checked", true); //是否选中
                    } else {
                        map1.put("checked", false);
                    }
                    Map<String, String> spec = (Map) JSON.parseObject(sku.getSpec()); // 当前sku
                    spec.put(key, value);
                    String jsonString = JSON.toJSONString(spec, SerializerFeature.MapSortField);
                    map1.put("url", urlMap.get(jsonString));
                    mapList.add(map1);// 用新集合替换旧集合
                }
                specMap.put(key, mapList);
            }
            map.put("specMap", specMap);
            // 上下文
            context.setVariables(map);
            //System.out.println(map);
            File dir = new File("D:\\item\\");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File dest = new File(dir, sku.getId() + ".html");
            try {
                PrintWriter writer = new PrintWriter(dest, "UTF-8");
                templateEngine.process("item", context, writer);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        }
    }
}
